package com.microsoft.socialphoto.ui;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.microsoft.socialphoto.Config;
import com.microsoft.socialphoto.R;
import com.microsoft.socialphoto.RequestCode;
import com.microsoft.socialphoto.SocialActivity;

public class UploadPhoto extends SocialActivity {

	private ImageView ivPhoto;
	private EditText etFileName;
	private Bitmap imageData;
	private LocationManager locmgr;
	private double mLong;
	private double mLat;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_upload);
		initControls();
		initVariables();

		Intent intent2 = new Intent("android.media.action.IMAGE_CAPTURE");
		startActivityForResult(intent2, RequestCode.GET_CAMERA);

		locmgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locmgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
				10000.0f, onLocationChange);
	}

	// pauses listener while app is inactive
	@Override
	public void onPause() {
		super.onPause();
		locmgr.removeUpdates(onLocationChange);
	}

	// reactivates listener when app is resumed
	@Override
	public void onResume() {
		super.onResume();
		locmgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
				10000.0f, onLocationChange);
	}

	// Start a location listener
	LocationListener onLocationChange = new LocationListener() {

		public void onLocationChanged(Location loc) {
			// sets and displays the lat/long when a location is provided
			mLong = loc.getLongitude();
			mLat = loc.getLatitude();

			Toast.makeText(getApplicationContext(), mLong + " - " + mLat,
					Toast.LENGTH_SHORT).show();
		}

		public void onProviderDisabled(String provider) {
			// required for interface, not used
		}

		public void onProviderEnabled(String provider) {
			// required for interface, not used
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// required for interface, not used
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			if (requestCode == RequestCode.GET_CAMERA) {
				imageData = (Bitmap) data.getExtras().get("data");
				ivPhoto.setImageBitmap(imageData);
			}
		}
	}

	private void initControls() {
		ivPhoto = (ImageView) findViewById(R.id.photo);
		etFileName = (EditText) findViewById(R.id.file_name);
	}

	private void initVariables() {

	}

	public void upload(View v) {
		String file_name = etFileName.getText().toString();
		boolean status = executeMultipartPost(file_name);

		if (status) {
			setResult(RESULT_OK);
			finish();
		}
	}

	private boolean executeMultipartPost(String file_name) {
		boolean status = false;

		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			imageData.compress(CompressFormat.JPEG, 90, bos);
			byte[] data = bos.toByteArray();
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost postRequest = new HttpPost(Config.UPLOAD_URL);
			ByteArrayBody bab = new ByteArrayBody(data, file_name + ".jpg");
			MultipartEntity reqEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			reqEntity.addPart("files", bab);
			reqEntity.addPart("photoCaption", new StringBody(file_name));
			reqEntity.addPart("longitude", new StringBody(mLong + ""));
			reqEntity.addPart("latitude", new StringBody(mLat + ""));

			postRequest.setEntity(reqEntity);
			HttpResponse response = httpClient.execute(postRequest);
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			String sResponse;
			StringBuilder s = new StringBuilder();

			while ((sResponse = reader.readLine()) != null) {
				s = s.append(sResponse);
			}
			System.out.println("Response: " + s);
		} catch (Exception e) {
			// handle exception here
			Log.e(e.getClass().getName(), e.getMessage());
		} finally {
			status = true;
		}

		return status;
	}
}
